`<template>
  <div class="container">
    <el-form
      :model="formData"
      :rules="rules"
      ref="formData"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="当前密码" prop="password">
        <el-input v-model="formData.password" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password2">
        <el-input v-model="formData.password2" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password3">
        <el-input v-model="formData.password3" style="width: 300px"></el-input>
      </el-form-item>
      <el-button type="primary" style="margin-left: 160px" class="button" @click="updatePassword()"
        >点击提交修改</el-button
      >
    </el-form>
  </div>
</template>
<script>
import request from '@/api/request'

export default {
  data() {
    return {
      formData: {
        password: '',
        password2: '',
        password3: '',
      },

      rules: {
        password: [
          {
            required: true,
            message: '请输入旧密码',
            trigger: 'blur',
          },
          {
            min: 6,
            max: 18,
            message: '长度在 6 到 18 个字符',
            trigger: 'blur',
          },
          {
            pattern: /^(\w){6,18}$/,
            message: '只能输入6-18个字母、数字、下划线',
            trigger: 'blur',
          },
        ],
        password2: [
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur',
          },
          {
            min: 6,
            max: 18,
            message: '长度在 6 到 18 个字符',
            trigger: 'blur',
          },
          {
            pattern: /^(\w){6,18}$/,
            message: '只能输入6-18个字母、数字、下划线',
            trigger: 'blur',
          },
        ],
        password3: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.formData.password2) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    updatePassword() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          request
            .patch('/admin/updatePwd', {
              password: this.formData.password,
              newPwd: this.formData.password2,
            })
            .then((res) => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('修改密码成功')
              }
            })
            .catch((error) => {
              this.$message.error(error)
            })
        }
      })
    },
  },
}
</script>

<style scoped>
.container {
  width: 50px;
  padding-top: 50px;
}
.demo-ruleForm{
  margin-left: 5%;
  margin-top: 6%;
}

</style>
